/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import $ from 'jquery';
import { Button, Classes, Dialog, Intent, Position } from '@blueprintjs/core';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { CopyToClipboard } from 'react-copy-to-clipboard';

// Utils
import { Saiku } from '../../../utils';

class ShowMdxDialog extends Component {
  state = {
    heightCode: 420
  };

  componentWillMount() {
    const height = $('body').height() / 2 + $('body').height() / 6;

    if (height > 420) {
      this.setState({ heightCode: 420 });
    } else {
      this.setState({ heightCode: height });
    }
  }

  handleCopy = () => {
    Saiku.toasts(Position.TOP_RIGHT).show({
      icon: 'tick',
      intent: Intent.SUCCESS,
      message: 'Copied!',
      timeout: 2000
    });
  };

  render() {
    const { query } = this.props;
    const { heightCode } = this.state;
    const mdx = query && query.mdx ? query.mdx : '';

    return (
      <Dialog
        title="Show MDX"
        icon="code"
        canOutsideClickClose={false}
        isOpen={true}
        onClose={this.props.onClose}
        style={{ width: '600px' }}
      >
        <div className={Classes.DIALOG_BODY}>
          <SyntaxHighlighter
            language="sql"
            style={docco}
            customStyle={{ height: heightCode }}
            showLineNumbers
          >
            {mdx}
          </SyntaxHighlighter>
        </div>

        <div className={Classes.DIALOG_FOOTER}>
          <div className={Classes.DIALOG_FOOTER_ACTIONS}>
            <CopyToClipboard text={mdx} onCopy={this.handleCopy}>
              <Button text="Copy" intent={Intent.DANGER} />
            </CopyToClipboard>
            <Button text="Close" onClick={this.props.onClose} />
          </div>
        </div>
      </Dialog>
    );
  }
}

ShowMdxDialog.propTypes = {
  query: PropTypes.object.isRequired,
  onClose: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  ...state.query
});

export default connect(mapStateToProps)(ShowMdxDialog);
